/**
 * 初始化表格和字段配置
 */

import { ElMessage } from 'element-plus';
import { setAPIConfig } from './dealData';

const fieldConfigDefault: fieldConfig = {
    fieldCode: '',
    fieldName: '',
    fieldLabel: '',
    fieldContentType: '',
    fieldWidth: 150,
    isTranslate: false,
    translateFieldCode: '',
    isRequired: false,
    isAttachment: false,
    uploadAllowFile: '*',
    isDefaultValue: false,
    isShow: true,
    isShowInTable: true,
    isQueryCondition: false,
    isSupportFuzzyQuery: false,
    optionDataApi: ''
};
const tableGridConfigDefault: formTableConfig = {
    isAddable: true,
    isEditable: true,
    isDeletable: true,
    isQueriable: true,
    addFunctionApi: '',
    editFunctionApi: '',
    deleteFunctionApi: '',
    uploadFileApi: '',
    deleteFileApi: '',
    tableDataApi: '',
    fieldConfigs: []
};
let attachmentFields: Array<any> = [];
let numberFields: Array<any> = [];

const getFieldConfig = (_tableGridConfig: formTableConfig, selfConfig: fieldConfig) => {
    const _fieldConfig = Object.assign({}, fieldConfigDefault, selfConfig);
    try {
        if (_fieldConfig.isShow && !_fieldConfig.isDefaultValue) {
            if (!_fieldConfig.fieldCode) {
                throw new Error('请指定fieldConfig的fieldCode字段');
            }
            if (!_fieldConfig.fieldName) {
                throw new Error(`请指定${_fieldConfig.fieldCode}配置的fieldName字段`);
            }
            if (
                _fieldConfig.fieldType === 'ElCheckboxGroup' ||
                _fieldConfig.fieldType === 'ElRadioGroup' ||
                _fieldConfig.fieldType === 'ElSelect' ||
                _fieldConfig.fieldType === 'ElTreeSelect'
            ) {
                if (!_fieldConfig.optionDataApi) {
                    throw new Error(`请指定${_fieldConfig.fieldName}配置的optionDataApi字段`);
                }
                if (!_fieldConfig.isTranslate) {
                    _fieldConfig.isTranslate = true;
                }
            }
            if (_fieldConfig.isTranslate) {
                if (!_fieldConfig.translateFieldCode) {
                    throw new Error(`请指定${_fieldConfig.fieldName}配置的translateFieldCode字段`);
                }
            }
            // 数字类型字段处理
            if (
                _fieldConfig.fieldType === 'ElInput' &&
                (_fieldConfig.fieldContentType === 'number' ||
                    _fieldConfig.fieldContentType === 'integer' ||
                    _fieldConfig.fieldContentType === 'float')
            ) {
                numberFields.push(Object.assign({}, _fieldConfig));
            }
    
            // 文件上传字段的处理
            if (_fieldConfig.fieldType === 'ElImgList' || _fieldConfig.fieldType === 'ElUpload') {
                if (!_fieldConfig.isAttachment) {
                    _fieldConfig.isAttachment = true;
                }
                if (_tableGridConfig.isAddable) {
                    if (!_tableGridConfig.uploadFileApi) {
                        throw new Error(
                            '若允许添加记录，请配置uploadFileApi，否则请将isAddable配置为false'
                        );
                    }
                    if (!_tableGridConfig.deleteFileApi) {
                        throw new Error(
                            '若允许添加记录，请配置deleteFileApi，否则请将isAddable配置为false'
                        );
                    }
                }
                if (_tableGridConfig.isEditable) {
                    if (!_tableGridConfig.uploadFileApi) {
                        throw new Error(
                            '若允许编辑记录，请配置uploadFileApi，否则请将isAddable配置为false'
                        );
                    }
                    if (!_tableGridConfig.deleteFileApi) {
                        throw new Error(
                            '若允许编辑记录，请配置deleteFileApi，否则请将isAddable配置为false'
                        );
                    }
                }
                attachmentFields.push(Object.assign({}, _fieldConfig));
            }
        }
    } catch (error: any) {
        ElMessage.error('表格配置出现错误！');
        throw new Error(error.message);
    }
    return _fieldConfig;
};

export const initConfig = (tableGridId: string, tableGridConfig: formTableConfig) => {
    attachmentFields = [];
    numberFields = [];
    const _tableGridConfig = Object.assign({}, tableGridConfigDefault, tableGridConfig);
    // 验证tableGrid配置的合法性
    try {
        if (_tableGridConfig.isAddable) {
            if (!tableGridConfig.addFunctionApi) {
                throw new Error('若允许添加记录，请配置addFunctionApi，否则请将isAddable配置为false');
            }
        }
        if (_tableGridConfig.isEditable) {
            if (!tableGridConfig.editFunctionApi) {
                throw new Error('若允许添加记录，请配置editFunctionApi，否则请将isEditable配置为false');
            }
        }
        if (_tableGridConfig.isDeletable) {
            if (!tableGridConfig.deleteFunctionApi) {
                throw new Error(
                    '若允许添加记录，请配置deleteFunctionApi，否则请将isDeletable配置为false'
                );
            }
        }
    } catch (error: any) {
        ElMessage.error('表格配置出现错误！');
        throw new Error(error.message);
    }

    let fieldConfigArr: fieldConfig[] = [];
    tableGridConfig.fieldConfigs.forEach((item: fieldConfig) => {
        fieldConfigArr.push(getFieldConfig(_tableGridConfig, item));
    });
    // 将API传至统一数据操作模块
    setAPIConfig(tableGridId, {
        addFunctionApi: _tableGridConfig.addFunctionApi,
        editFunctionApi: _tableGridConfig.editFunctionApi,
        deleteFunctionApi: _tableGridConfig.deleteFunctionApi,
        uploadFileApi: _tableGridConfig.uploadFileApi,
        deleteFileApi: _tableGridConfig.deleteFileApi,
        tableDataApi: _tableGridConfig.tableDataApi,
        attachmentFields: JSON.parse(JSON.stringify(attachmentFields)),
        numberFields: JSON.parse(JSON.stringify(numberFields))
    });
    _tableGridConfig.fieldConfigs = fieldConfigArr;
    return _tableGridConfig;
};
